<template>
	<view class="container">
		<view class="closeempty">
			<uni-icons @click="closePopup" color="#323232" type="closeempty" size="16"></uni-icons>
		</view>
		<view class="content" v-if="orderDetail.comboId" >
			<view class="head_box">
				<view class="head_title">
					<image class="main_img" v-if="orderDetail.coverImage && orderDetail.coverImage.length > 0" :src="orderDetail.coverImage[0].url" mode="">
					</image>
					<view  style="height: 112px;" v-else>
						
					</view>
					<view class="m-l12 head_t">
						<view class="f18" >
							{{orderDetail.comboName}}
						</view>
						<view class="txt flex_align_conter m-t4">
					<!-- 		<view class="f18">
								库存：{{(orderDetail.num - orderDetail.sales) || 0}}
							</view> -->
							<view class="m-l12 f18" v-if="orderDetail.isHeat">
								热量：{{orderDetail.heat || 0}}千卡
							</view>
					<!-- 		<view class="m-l12 f18" v-if="orderDetail.isSaleAllNum">
								积累销量:{{orderDetail.saleAllNum || ''}}
							</view> -->
							<view class="m-l12 f18" v-if="orderDetail.isAllergy">
								过敏源:{{orderDetail.allergy || ''}}
							</view>
						</view>
					</view>
				</view>
				<view class="m-t8 describe_b f18">
					{{orderDetail.description}}
				</view>
			</view>
			<view class="food_list m-t20" v-if="listItem && listItem.length> 0">
				<view class="food_item " v-for="item in listItem">
					<view class="">
						<view class=" m-b8 f18">
							{{estimateCuisineType(item.type)}}
						</view>
						<view class="food_item_c flex">
							<image class="food_img" v-if="item.foodDish.image && item.foodDish.image.length > 0" :src="item.foodDish.image[0].url"
								mode="">
							</image>
					
							<view class="m-l10 flex1 f18">
								<view class="flex_between f18">
									<view class=" f18" v-if="item.foodDish">
										{{item.foodDish.foodName || ''}}
										<text v-if="item.foodDish.huisType==1" style="padding-left: 5rpx;">🐷</text>
										<text v-if="item.foodDish.peType==1" style="padding-left: 5rpx;">🌶</text>
										<text v-if="item.foodDish.peType==2" style="padding-left: 5rpx;">🌶</text>
										<text v-if="item.foodDish.peType==2" style="padding-left: 5rpx;">🌶</text>
										<text v-if="item.foodDish.peType==3" style="padding-left: 5rpx;">🌶</text>
										<text v-if="item.foodDish.peType==3" style="padding-left: 5rpx;">🌶</text>
										<text v-if="item.foodDish.peType==3" style="padding-left: 5rpx;">🌶</text>
									</view>
									<view class="t flex_align_conter">
										<view class="f18" v-if="item.foodDish.heat">
											热量：{{item.foodDish.heat || 0}}千卡
										</view>
										<view class="m-l8 f18" v-if="item.foodDish.taste">
											{{item.foodDish.taste || ''}}
										</view>
									</view>
								</view>
								<view class="txt f18">
									<view class=" m-b2" v-if="item.foodDish.foodIngredientsDishList && item.foodDish.foodIngredientsDishList.length > 0">
										食材：<span v-for="(items,index) in item.foodDish.foodIngredientsDishList"
											:key="index">
											{{ items.ingredientsName + (index == (item.foodDish.foodIngredientsDishList.length -1) ? "" : "，") }}
										</span>
									</view>
									<view class="f18" v-if="item.foodDish.description">
										过敏源：{{item.foodDish.description || ""}}
										</span>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

		</view>
		<view class="footer">
			<view class="flex_between">
				<view class="flex_align_conter f18" style="padding-top: 18rpx;">
					￥<text v-if="orderDetail.isPrice" style="font-size: 44rpx;margin-left: 4rpx;">{{orderDetail.price || ''}}</text>
					<text v-if="orderDetail.isOriginalPrice" style="text-decoration: line-through;padding-left: 10rpx;">￥<text  style="font-size: 26rpx;margin-left: 4rpx;">{{orderDetail.originalPrice || 0}}</text></text>
	<!-- 				<text
						style="margin-left: 20rpx;font-size: 24rpx;" class="f18">库存：{{ orderDetail.num - orderDetail.sales }}</text> -->
				</view>
				<button v-if="showShopping" class="confirm-btn cu-btn bg-green round "
					@click="addShopping">加入购物车</button>
			</view>
		</view>
	</view>
</template>

<script>
	// import {
	// 	mapState
	// } from 'vuex';
	import tab from '../../plugins/tab'
import {
		// getUnitTypeAPI,
		getComboDetailAPI,
		getCuisineTypeAPI,
		getComboDetailAPI2
	} from '@/api/index.js'
	export default {
		props: {
			showShopping: {
				type: Boolean,
				default: true
			},
			comboId: {
				type: Number,
				default: 0
			},
			date:{
				type:String,
				default:""
			}
		},
		data() {
			return {
				orderDetail: {},
				listItem: [],
				cuisineType: [],
				tableColumn:[],//套餐
				tableCuisine:[]//菜品
			}
		},
		computed: {},
		mounted() {
			// if (this.comboId) {
			this.getCuisineType()

			// }

		},
		methods: {
			estimateCuisineType(e) {
				return this.cuisineType.filter(item => item.dictValue == e)[0].dictLabel
			},
			async getCuisineType() {
				const res = await getCuisineTypeAPI()
				// console.log(res);
				this.cuisineType = res.data
				this.getComboDetail()
			},
			addShopping() {
				this.$emit('addShopping')
			},
			insertPropertyByDictLabel(arr, mapping) {
			  // 深拷贝原数组，避免修改原数据
			  return JSON.parse(JSON.stringify(arr)).map(item => {
			    // 检查当前对象是否有dictLabel属性
			    if (item && item.dictLabel !== undefined) {
			      // 查找对应的映射关系
			      const propertyMap = mapping[item.dictLabel];
			      // 如果存在映射关系，则添加对应的属性
			      if (propertyMap && typeof propertyMap === 'object') {
			        return {
			          ...item,
			          ...propertyMap
			        };
			      }
			    }
			    // 如果没有匹配的映射关系，返回原对象
			    return item;
			  });
			},
			updateObjectByDictLabelKey(arr, obj) {
			    // 深拷贝原对象，避免修改原始数据
			    const newObj = JSON.parse(JSON.stringify(obj));
			    
			    // 遍历数组中的每个对象
			    arr.forEach(item => {
			        // 检查当前对象是否有dictLabelKey属性
			        if (item && item.dictLabelKey) {
			            const key = item.dictLabelKey;
			            // 检查目标对象是否包含该属性
			            if (newObj.hasOwnProperty(key)) {
			                // 这里将值改为true，您可以根据需要修改为其他值
			                newObj[key] = true;
			            }
			        }
			    });
			    
			    return newObj;
			},
			isThisWeek(dateStr) {
			  // 将日期字符串转换为 Date 对象
			  const date = new Date(dateStr);
			  const year = date.getFullYear();
			  const month = date.getMonth();
			  const day = date.getDate();
			
			  // 获取当前日期
			  const now = new Date();
			  const nowYear = now.getFullYear();
			  const nowMonth = now.getMonth();
			  const nowDay = now.getDate();
			
			  // 获取本周的第一天（周日）和最后一天（周六）
			  const startOfWeek = new Date(nowYear, nowMonth, nowDay - now.getDay());
			  const endOfWeek = new Date(nowYear, nowMonth, nowDay + (6 - now.getDay()));
			
			  // 检查给定日期是否在本周范围内
			  return date >= startOfWeek && date <= endOfWeek;
			},
			isThisWeek(dateStr) {
			  // 将日期字符串转换为 Date 对象
			  const date = new Date(dateStr);
			  const year = date.getFullYear();
			  const month = date.getMonth();
			  const day = date.getDate();
			
			  // 获取当前日期
			  const now = new Date();
			  const nowYear = now.getFullYear();
			  const nowMonth = now.getMonth();
			  const nowDay = now.getDate();
			
			  // 获取本周的第一天（周日）和最后一天（周六）
			  const startOfWeek = new Date(nowYear, nowMonth, nowDay - now.getDay());
			  const endOfWeek = new Date(nowYear, nowMonth, nowDay + (6 - now.getDay()));
			
			  // 检查给定日期是否在本周范围内
			  return date >= startOfWeek && date <= endOfWeek;
			},
			async getComboDetail() {
				// uni.showLoading({
				// 	title: '正在加载数据',
				// })
				console.log(this.date)
				console.log(this.isThisWeek(this.date))
				let res;
				if(this.isThisWeek(this.date)){
					res = await getComboDetailAPI2({
						comboId:this.comboId,
						date:this.date
					})
				}else{
					res = await getComboDetailAPI(this.comboId)
				}
				// uni.hideLoading()
				this.orderDetail = res.data
				
				console.log('获取orderDetail', this.orderDetail)
				// 用于判断是否显示对应字段逻辑
				this.$set(this.orderDetail,'isAllergy',false)//是否显示过敏原
				this.$set(this.orderDetail,'isHeat',false)//是否显示热量
				this.$set(this.orderDetail,'isListItem',false)//是否显示菜品
				this.$set(this.orderDetail,'isOriginalPrice',false)//是否显示原价
				this.$set(this.orderDetail,'isPrice',false)//是否显示现售价
				this.$set(this.orderDetail,'isSaleAllNum',false)//是否显示积累销量
				// 定义映射关系：key是dictLabel的值，value是要插入的属性键值对
				const labelMapping = {
				  "热量": { 
				    dictLabelKey: 'isHeat'
				  },
				  "积累销量": { 
				     dictLabelKey: 'isSaleAllNum'
				  },
				  "过敏源": { 
				    dictLabelKey: "isAllergy", 
				  },
				  "菜品": {
				    dictLabelKey: "isListItem", 
				  },
				  "现售价": {
				    dictLabelKey: "isPrice", 
				  },
				  "原价": {
				    dictLabelKey: "isOriginalPrice", 
				  }
				};
				// 调用函数
				const result = this.insertPropertyByDictLabel(this.tableColumn, labelMapping);
				console.log('调用函数结果result', result)
				// 调用函数
				const updatedObj = this.updateObjectByDictLabelKey(result, res.data);
				this.orderDetail=updatedObj
				if (res.data.coverImage) {
					this.orderDetail.coverImage = JSON.parse(res.data.coverImage)
				}
				this.listItem = res.data.listItem.map(item => {
					if (item.foodDish && item.foodDish.image) {
						item.foodDish.image = JSON.parse(item.foodDish.image)
					}
					return item
				})
			},
			closePopup() {
				// console.log('closePopup');
				this.$emit('closePopup')
				// this.$refs.popup.close()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		width: 100%;
		min-height: 400rpx;
		background-color: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 30rpx 40rpx 40rpx;

		.food_list {
			max-height: 700rpx;
			overflow-y: auto;

			.food_item {
				margin-bottom: 32rpx;
			}

			.food_item_c {
				.t {
					color: #0EB275;
					font-size: 24rpx;
				}

				.txt {
					margin-top: 24rpx;
				}
			}

			.food_img {
				width: 132rpx;
				height: 132rpx;
				border-radius: 16rpx;
			}
		}

		.content {
			position: relative;
			top: -90rpx;
		}

		.head_box {
			.describe_b {
				font-size: 20rpx;
				font-weight: 350;
			}

			.txt {
				font-size: 16rpx;
				font-weight: 350;
			}

			.head_t {
				padding-bottom: 20rpx;
			}

			.head_title {
				display: flex;
				align-items: flex-end;
				// margin-bottom: 30rpx;
			}
		}




		.main_img {
			width: 200rpx;
			height: 200rpx;
			border-radius: 32rpx;
		}

		.closeempty {
			position: absolute;
			top: 30rpx;
			right: 30rpx;
			z-index: 9;
			// display: flex;
			// justify-content: end;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		background: #FFFFFF;
		box-shadow: 0px 4px 20px 0px rgba(0, 0, 0, 0.1);
		text-align: center;
		// margin-top: 40rpx;
		padding: 20rpx 40rpx;
		width: 100%;

		.confirm-btn {
			width: 248rpx;
		}
	}
</style>